const { createProject, findProject, updateProject, deleteProject } = require("../db/project");
const { ErrorModel, SuccessModel } = require("../model/resModel");
const { isRequiredParams } = require("../utils/tool");

const ProjectCtl = {
  /**
   * @api {post} /project/create 新建工程
   * @apiName 新建工程
   * @apiGroup Project
   *
   * @apiParam {string} name 用户名【必填】
   * @apiParam {string} userId 用户ID
   * @apiParam {Json} rooms 房间信息
   * [{
          "name": "room1",
          "totalPrice": 111,
          "place": [
              {
                  "width": 1.2,
                  "height": 2.2,
                  "price": 40
              }
          ]
      }]
   *
   * @apiSuccess {JSON} 自己看返回.
   */
  create: async (ctx) => {
    const body = ctx.request.body;
    const userId = ctx.headers.userId;
    const { err, msg } = isRequiredParams(["name"], body);
    if (err) {
      ctx.body = new ErrorModel(msg);
      return;
    }
    let res = await createProject({ userId, ...body });
    if (res.err) {
      ctx.body = new ErrorModel("创建失败！");
      return;
    }
    ctx.body = new SuccessModel(res, "创建成功");
  },
  search: async (ctx) => {
    const params = ctx.query;
    const userId = ctx.headers.userId;
    const res = await findProject({ userId, ...params });
    if (res.err) {
      ctx.body = new ErrorModel("查询失败");
      return;
    }
    ctx.body = new SuccessModel(res);
  },
  find: async (ctx) => {
    const { id } = ctx.params;
    const res = await findProject({ id });
    if (res.err) {
      ctx.body = new ErrorModel("查询失败");
      return;
    }
    ctx.body = new SuccessModel(res[0]);
  },
  update: async (ctx) => {
    const data = ctx.request.body;
    const { id } = ctx.params;
    const res = await updateProject(id, data);
    if (res.err) {
      ctx.body = new ErrorModel("更新失败");
      return;
    }
    ctx.body = new SuccessModel(res);
  },
  destroy: async (ctx) => {
    const { id } = ctx.params;
    const res = await deleteProject(id);
    if (res) {
      ctx.body = new SuccessModel("删除成功");
      return;
    }
    ctx.body = new ErrorModel("删除失败");
  },
};

module.exports = ProjectCtl;
